/* Copyright Florian Schweitzer
 * File created 04.12.2012
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */
package org.openuat.android.demo;

import org.openuat.android.demo.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Class to show discovered OpenUAT devices (e.g. with Bluetooth)
 * @author Florian Schweitzer
 *
 */
public class DeviceListActivity extends Activity {
    //Intent extras
    public static final String CHOSEN_DEVICE = "device";

    private static ArrayAdapter<String> mOpenUATDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.device_list);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setTitle("Discovering OpenUAT-Service Devices...");

        setResult(Activity.RESULT_CANCELED);
        
        mOpenUATDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);        

        ListView openUATDevicesListView = (ListView) findViewById(R.id.openuat_devices);
        openUATDevicesListView.setAdapter(mOpenUATDevicesArrayAdapter);
        openUATDevicesListView.setOnItemClickListener(mDeviceClickListener);
    }
    
    /**
     * Sets the discovered devices
     * @param devices		The discovered devices
     */
    public static void setDevices(String[] devices) {
    	if (mOpenUATDevicesArrayAdapter != null) {
    		mOpenUATDevicesArrayAdapter.clear();
        	
        	for (String dev : devices) {
        		mOpenUATDevicesArrayAdapter.add(dev);    		
        	}    		
    	}
    }

    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();

            // Result intent
            Intent intent = new Intent();
            intent.putExtra(CHOSEN_DEVICE, info);

            // Set result and finish this Activity
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };
}
